package com.lw.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lw.client.DepartmentFeignClient;
import com.lw.service.PermissionService;
import com.lw.service.RoleService;
import com.lw.service.UserService;
import com.lw.system.ProfileResult;
import com.lw.system.Role;
import com.lw.system.User;
import com.lw.util.excel.ExcelExportUtil;
import com.lw.util.excel.ExcelImportUtil;
import com.lw.utils.*;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    //查找企业所有员工并查找用户所拥有的角色
    @Autowired
    UserService userService;
    @Autowired
    IdWorker idWorker;
    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    PermissionService permissionService;
    @PostMapping("/upload/{id}")
    public Result staffPhoto(@PathVariable("id") String id,@RequestPart(name = "file") MultipartFile file) throws IOException {
        //1.对图片进行编码处理 在service操作（储存图片的访问地址dataUrl或者http地址）
        userService.uploadImg(id,file);
        //2.返回数据
        return new Result( ResultCode.SUCCESS );
    }
    @GetMapping("/findAll")
    public Result findAll(@RequestParam Map<String,Object> map){
        Page<User> all = userService.findAll(map);
        return new Result( ResultCode.SUCCESS,all );
    }

    /**
     * 根据id查找用户
     * @return
     */
    @GetMapping("/findById")
    public Result findById(@RequestParam(value = "id") String id){
        User user = userService.getById( id );
        return new Result( ResultCode.SUCCESS,user );
    }

    /**
     * 根据id删除员工
     * @return
     */
    @DeleteMapping("/delete")
    public Result delete(@RequestBody Map<String,String> map){
        userService.removeById( map.get( "id" ) );
        return Result.SUCCESS();
    }
    /**
     * 更新或保存用户
     * @return
     */
    @PostMapping("/edit")
    public Result edit(@RequestBody User user){
        User temp=null;
        if (user.getId()!=null){
            temp=user;
        }else {
            String id=idWorker.nextId()+"";
            temp=user;
            temp.setId( id );
            temp.setCompanyId( companyId );
            temp.setPassword( "123456" );//设置初始密码
            temp.setEnableState( 1 );//默认可用
        }
        userService.saveOrUpdate( temp );
        return Result.SUCCESS();
    }
    @GetMapping("/findOtherRoles")
    public Result findOtherRoles(@RequestParam(value = "id") String id){
        List<Role> otherRoles = userService.findOtherRoles( id );
        return new Result( ResultCode.SUCCESS,otherRoles );
    }
    @PostMapping("/assignRoles")
    public Result assignRoles(@RequestBody Map<String, Object> map){
        userService.assignRoles( map );
        return Result.SUCCESS();
    }

    /**
     * 用户登录
     * 1通过mobile查询用户
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map<String,Object> map){
        //1.构造登陆令牌
        try {
            String mobile = (String) map.get( "mobile" );
            String password = (String) map.get( "password" );
            UsernamePasswordToken token = new UsernamePasswordToken( mobile, password );
            //2.获取subject
            Subject subject = SecurityUtils.getSubject();
            //3.调用login方法 捕获异常
            subject.login( token );
            //4.获取sessionId
            String id = (String) subject.getSession().getId();
            //4.构造返回结果
            return new Result( ResultCode.SUCCESS,id );
        }catch (Exception e){
            return Result.FAIL();
        }

//        User user = userService.getOne( new QueryWrapper<User>().eq( "mobile", map.get( "mobile" ) ) );
//        if (user==null||!map.get( "password" ).equals( user.getPassword() )){
//            //登陆失败
//            return new Result(ResultCode.LOGIN_FAIL);
//        }else {
//            //登陆成功
//            //api权限字符串
//            User byId = userService.findById( user.getId() );
//            StringBuilder sb=new StringBuilder();
//            for (Role role:byId.getRoles()){
//                for (Permission permission:role.getPermissions()){
//                    if (permission.getType()==3){
//                        sb.append( permission.getCode() ).append( "," );
//                    }
//                }
//            }
//            Map<String,Object> map1=new HashMap<>();
//            map1.put( "apis",sb );
//            map1.put( "companyId",user.getCompanyId() );
//            map1.put( "companyName",user.getCompanyName() );
//            String token=jwtUtils.createJwt( user.getId(),user.getUsername(),map1 );
//            return new Result( ResultCode.SUCCESS,token );
//        }
    }
    @PostMapping("/profile")
    public Result profile(HttpServletRequest request){
        //获取session中的安全数据
        Subject subject=SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        ProfileResult result = (ProfileResult) principals.getPrimaryPrincipal();
        return new Result( ResultCode.SUCCESS,result );
    }
//        Claims claims= (Claims) request.getAttribute( "claims" );//从请求域中获取
//        String userId = claims.getId();
//        User  user= userService.findById( userId );
//        ProfileResult profileResult = null;
//        //根据用户等级获取用户权限 saas管理员具有所有权限
//        if ("saasAdmin".equals( user.getLevel() )){
//            List<Permission> permissions = permissionService.list();
//            profileResult=new ProfileResult( user,permissions );
//        }else if ("coAdmin".equals( user.getLevel() )){
//            List<Permission> permissions = permissionService.list( new QueryWrapper<Permission>().eq( "en_visible", 1 ) );
//            profileResult=new ProfileResult( user,permissions );
//        }else {
//            profileResult=new ProfileResult( user );
//        }
//            return new Result( ResultCode.SUCCESS,profileResult);
//    }
    @Autowired
    private DepartmentFeignClient departmentFeignClient;
    /**
     * 测试feign组件
     * 调用系统微服务的/test接口传递部门id，通过feign调用部门微服务获取部门信息
     */
    @GetMapping("/test/{id}")
    public Result testFeign(@PathVariable("id") String id){
        Result result = departmentFeignClient.findById( id );
        return result;
    }

    /**
     * 解析上传的excel
     * 用导入用户进行测试
     * @param file
     * @return
     */
    @PostMapping("/import")
    public Result importUser(@RequestPart("file")MultipartFile file) throws IOException {
        //1.根据Excel文件创建工作簿
//        Workbook wb=new XSSFWorkbook( file.getInputStream() );
//        //2获取sheet
//        Sheet sheet = wb.getSheetAt( 0 );
//        //3.获取sheet中的每一行，和每一个单元格
//        List<User> list=new ArrayList<>();
//        for (int rowNum=1;rowNum<sheet.getLastRowNum()+1;rowNum++){
//            Row row = sheet.getRow( rowNum );//根据索引获取每一行
//            Object[] values=new Object[row.getLastCellNum()];
//            for (int cellNum=1;cellNum<row.getLastCellNum();cellNum++){
//                //根据索引获取每一个单元格
//                Cell cell = row.getCell( cellNum );
//                //获取每一个单元格的内容
//                Object value=getCellValue( cell );
//                values[cellNum]=value;
//            }
//            User user=new User(values);
//            list.add( user );
//        }
        //对用户实体类进行注解操作 才能完成正常运行 可以把部门编码放置在部门id上
        List list = new ExcelImportUtil( User.class ).readExcel( file.getInputStream(), 1, 1 );
        //批量保存用户
        userService.saveBatch( list );//没有写全 没设置id 没设置所属公司
        return Result.SUCCESS();
    }
//    public static Object getCellValue(Cell cell){
//        //1.获取单元格的属性类型
//        CellType cellType = cell.getCellType();
//        //2.根据单元格数据类型获取数据
//        Object value=null;
//        switch (cellType){
//            case STRING:
//                value=cell.getStringCellValue();
//                break;
//            case BOOLEAN:
//                value=cell.getBooleanCellValue();
//                break;
//            case NUMERIC:
//                //日期格式
//                if (DateUtil.isCellDateFormatted( cell )){
//                    value=cell.getDateCellValue();
//                }else {
//                    //数字
//                    value=cell.getNumericCellValue();
//                }
//                break;
//            case FORMULA:
//                value=cell.getCellFormula();
//                break;
//            default:
//                break;
//        }
//        return value;
//    }
    @Autowired
    RoleService roleService;

    /**
     * SXSSFWorkbook 不支持模板打印
     * 作用 打印百万数据报表
     * @throws IOException
     */
    @GetMapping("/export2")
    public void export2() throws IOException {
        //1.获取角色数据
        List<Role> list=roleService.list();
        //2.构造excel
        //创建工作簿
        Workbook wb=new SXSSFWorkbook();//默认超出100个对象 将其它对象存储到临时文件
        //构造sheet
        Sheet sheet = wb.createSheet();
        //创建行
        //标题
        String[] titles="编号,名称,描述".split( "," );
        //处理标题
        int titleIndex=0;
        Row row=sheet.createRow( 0 );
        for (String title:titles){
            Cell cell = row.createCell( titleIndex++ );
            cell.setCellValue( title );
        }
        //创建单元格
        int rowIndex=1;
        Cell cell=null;
        for (Role role:list){
            row= sheet.createRow( rowIndex++ );
            cell = row.createCell( 0 );
            cell.setCellValue( role.getId() );
            cell = row.createCell( 1 );
            cell.setCellValue( role.getName() );
            cell = row.createCell( 2 );
            cell.setCellValue( role.getDescription() );
        }
        //3.完成下载
        ByteArrayOutputStream os=new ByteArrayOutputStream();
        wb.write( os );
        new DownloadUtils().download( os,response,"角色报表.xlsx" );
    }

    /**
     * 使用模板打印 用角色表进行测试 工具类支持的是模板打印
     * @throws IOException
     */
    @GetMapping("/export1")
    public void export1() throws Exception {
        //1.获取角色数据
        List<Role> list=roleService.list();
        //2.加载模板
        Resource resource=new ClassPathResource( "excel-template/hr-demo.xlsx" );
        FileInputStream fis=new FileInputStream( resource.getFile() );
        //3.通过工具类下载文件
        //从第三行开始写数据，从第三行开始解决样式
        new ExcelExportUtil<Role>(Role.class,2,2  ).export(response,fis,list,"角色报表.xlsx"  );
        //3.根据模板创建工作簿
      /*  Workbook wb=new XSSFWorkbook( fis );
        //4.读取工作表
        Sheet sheet = wb.getSheetAt( 0 );
        //5.抽取公共样式
        Row row = sheet.getRow( 2 );
        CellStyle[] cellStyles = new CellStyle[row.getLastCellNum()];
        for (int i=0;i<row.getLastCellNum();i++){
            Cell cell = row.getCell( i );
            cellStyles[i]=cell.getCellStyle();
        }
        //6.构造单元格
        //创建单元格
        int rowIndex=2;
        Cell cell=null;
        for (Role role:list){
            row= sheet.createRow( rowIndex++ );
            cell = row.createCell( 0 );
            cell.setCellStyle( cellStyles[0] );
            cell.setCellValue( role.getId() );
            cell = row.createCell( 1 );
            cell.setCellStyle( cellStyles[1] );
            cell.setCellValue( role.getName() );
            cell.setCellStyle( cellStyles[2] );
            cell = row.createCell( 2 );
            cell.setCellValue( role.getDescription() );
        }
        //7.下载
        ByteArrayOutputStream os=new ByteArrayOutputStream();
        wb.write( os );
        new DownloadUtils().download( os,response,"角色报表.xlsx" );*/
    }
}
